﻿using B.S.Base.Read.API.Application.Command;
using MediatR;
using WEBAPI.API.Dto;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Read.API.Application.CommandHandLer
{
    public class GetMuneCommandHandLer : IRequestHandler<GetMuneCommand, APIResult<List<object>>>
    {
        private readonly IBaseRepostiy<MenuModel> mdal;
        private readonly IBaseRepostiy<MenuRoleModel> _menuRoleModel;
        public GetMuneCommandHandLer(IBaseRepostiy<MenuModel> mdal, IBaseRepostiy<MenuRoleModel> menuRoleModel)
        {
            this.mdal = mdal;
            this._menuRoleModel = menuRoleModel;
        }


        public  Task<APIResult<List<object>>> Handle(GetMuneCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<object>> result = new APIResult<List<object>>();

            result.Code = ResultCode.Ok;
            result.Message = ResultCode.Ok.ToString();
            var list = GetMuneSHowAll(0);
            List<int> mids = new List<int>();
            //通过角色编号查对应的菜单表
            if(request.Rid!=0)
            {
                mids = _menuRoleModel.GetAll().Where(x => x.Rid == request.Rid).Select(x => x.Mid).ToList();
            }
            result.Data = new()
            {
                list, mids
            };
            return Task.FromResult(result);
        }
        private  List<Mument> GetMuneSHowAll(int id)
        {
            try
            {
                var list =  mdal.GetAll().Where(x => x.Pid == id&&!x.IsDeleted).ToArray();
                List<Mument> muners = new List<Mument>();
                foreach (var item in list)
                {
                    muners.Add(new Mument
                    {
                        id = item.Id,
                        label = item.MenuName,
                        children =  GetMuneSHowAll(item.Id)
                    });
                }
                return muners;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
